<!--tvm票款差异协查-->
<template>
  <div class="dantaishebeipiaohuanchayi el-card is-always-shadow el-card__body">
    <avue-crud
      ref="dantaishebeipiaohuanchayi"
      :option="option"
      :table-loading="listLoading"
      :data="data"
      :page.sync="page"
      @search-change="handleFilter"
      @selection-change="selectionChange"
      @refresh-change="refreshChange"
      @on-load="refreshChange"
      :row-style="rowStyle"
      :cell-style="cellStyle">
      <template slot="menuRight">
        
	<el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('3')">下发设备部和车站协查</el-button>
	<el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('1')">下发设备部协查</el-button>
	<el-button type="primary" v-if="permissionList.sendStatus" size="mini" @click="sendStatus('2')">下发车站协查</el-button>
	<el-button type="primary" v-if="permissionList.replaceContent" size="mini" @click="replaceContentOne()">一键替换</el-button>
	<el-button type="primary"  size="mini" @click="delBatchs">删除</el-button>
     
<!--        <el-button type="primary"  size="mini" @click="exportData">导出</el-button>-->       
      </template>
      <template slot-scope="scope" slot="lineCodeSearch">
        <el-select v-model="searchForm.lineCode" placeholder="请选择" style="width: 150px" @change="changeLine">
          <el-option
            v-for="(item,index) in lineCodes"
            :key="index"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="stationCodeSearch">
        <el-select v-model="searchForm.stationCode" placeholder="请选择" style="width: 150px" @change="changeStation">
          <el-option
            v-for="(item,index) in stationCodes"
            :key="index"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="incomeTimeSearch">
        <el-date-picker
          v-model="searchForm.incomeTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="收入日期">
        </el-date-picker>
      </template>
      <template slot-scope="scope" slot="tvmCodeSearch">
        <el-select v-model="searchForm.tvmCode" placeholder="请选择" style="width: 150px" >
          <el-option
            v-for="(item,index) in tvmCodes"
            :key="index"
            :label="item.tvmCode"
            :value="item.tvmCode">
          </el-option>
        </el-select>
      </template>
      <template slot="searchMenu" slot-scope="{row,size}">
        <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);getList()}" icon="el-icon-delete">清空</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" v-if="((scope.row.assistInvestStatus==3 && scope.row.kyReplyStatus==1) || scope.row.replyStatus==1) && scope.row.replaceStatus == 0 && scope.row.assistCategory!='0'" size="small" plain @click.stop="previewEditor(scope.row)">回馈预览</el-button>
        
       <el-button type="text" v-if="!(((scope.row.assistInvestStatus==3 && scope.row.kyReplyStatus==1) || scope.row.replyStatus==1) && scope.row.replaceStatus == 0 && scope.row.assistCategory!='0')" size="small" plain @click.stop="previewEditor(scope.row)">预览</el-button>

	<!-- <el-button type="text" v-if="scope.row.replyStatus==1 && scope.row.replaceStatus=='0' && scope.row.assistCategory!='0' && scope.row.assistCategory!='2'" size="small" plain @click.stop="replaceContentOne(scope.row)">一键替换</el-button> -->
      </template>
    </avue-crud>
    <HuikuiInfo ref="HuikuiInfo" v-if="isShowDia"></HuikuiInfo>
</div>
</template>


<script>
    import {getForm, postForm} from '@/api/gen/gen'
    import moment from "moment";
    import HuikuiInfo from './HuikuiInfo';
    import {
      getSwAuTvmSingleAssistList,
      sendStatusSwAuTvmSingleAssist,setSwAuTvmSingleAssist,delBatch,
    } from "../../../../../api/subwayRat/TVMRevenueVarianceAudit.TvmChaYiDXC/dantaishebeipiaohuanchayi";
    import {
      fenExYuangettoFixed,
      getgetStationCodes,
      getLineCodes, getLineName, getRepalceStatus, getStationName, getUninstall,repalceStatus,
      getXieChaStatusFormat, replayStatus, setSearchFiledsEmpty, uninstall,
      xieChaStatus, getStationByCode,getLineAndStationByCode, getSwPmTvmCodeList,assistCategoryData,getAssistCategory
    } from "../../../../../api/subwayRat/commonCheck";
    import {exportDataToExcel} from "../../../../../api/subwayRat/exportSelf";
    import transitUtil from "../../../../../api/subwayRat/transitUtil";
    import {mapGetters} from "vuex";
    export default {
      components:{
        HuikuiInfo,
        moment
      },
      data() {
            return {
              isShowDia:false,
              listLoading: true,
              lineCodes:[],
              stationCodes:[],
              tvmCodes:[],
              selectKeys:[], //存放对像
              selectKeyVals:[], //存放值
              data: [],
              searchForm:{
                lineCode:'9',
                stationCode:''
              },
              page: {
                total: 0, // 总页数
                currentPage: 1, // 当前页数
                pageSize: 20, // 每页显示多少条,
                isAsc: false// 是否倒序
              },
              option:{
                emptyBtn:false,
                cancelBtn:false,
                editBtn:false,
                delBtn:false,
                addBtn:false,
                border: true,
                index:true,
                indexLabel:'序号',
                page:true,
                menuWidth:150,
                align:'center',
                menuAlign:'center',
                selection: true,
                reserveSelection:false,
                height: 500,
                column:[
                  {prop:'lineCode',label:'线路',width:100,type:'select',search:false,hide:true,searchslot:true,formatter: function(row, value , label, column){
                      return getLineName(value);
                    }},
                  {prop:'stationCode',label:'站点',width:180,search:true,searchslot:true,formatter: function(row, value , label, column){
                      return getStationName(row.lineCode,value);
                    }},
                  {prop:'tvmCode',label:'TVM编号',width:120,search:true,searchslot:true},
                  {prop:'incomeTime',width:120,type:"date",format:'yyyy-MM-dd',valueFormat:'yyyy-MM-dd',label:'收入日期',search:true,searchslot:true},
                  {prop:'boxUninstallStatus',width:120,label:'卸载状态',dicData:uninstall(),formatter:function(row, value , label, column){
                      return getUninstall(value);
                    }},
                  {label:"SC售卖金额",width:120,
                  "prop":"saleAmount",formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'saleAmount');
                    }},
                  {label:"SC充值金额",width:120,
                  "prop":"depositAmount",formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'depositAmount');
                    }},
                  {label:"SC退款金额",width:120,
                  "prop":"errorRefundAmount",formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'errorRefundAmount');
                    }},
                  {label:"系统金额",
                  "prop":"tvmBillOrderMoney",formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'tvmBillOrderMoney');
                    }},
                  {prop:'actualMoney',label:'实点金额',formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'actualMoney');
                    }},
                  {prop:'diffMoney',label:'差异金额',formatter:function (row,value , label, column) {
                      return fenExYuangettoFixed(row,'diffMoney');
                    }},
                  {label:"协查流程状态",width:120,prop:"assistInvestStatus",type:'select',search:true,searchLabelWidth:100,dicData:xieChaStatus(),formatter: function(row, value , label, column){
                    return getXieChaStatusFormat(value);
                  }},
                  {label:"机电协查状态",width:120,prop:"replyStatus",type:'select',search:true,searchLabelWidth:100,
                    dicData:[{
                      label: '未反馈',
                      value: 0
                    },{
                      label: '已反馈',
                      value: 1
                    }],
                    formatter:function(row, value , label, column){
                      return value == 0?'未反馈':'已反馈';
                    }
                   },
		  {prop:'assistCategory',label:'协查类型',dicData:assistCategoryData(),type:'select',search:true,
                    formatter:function(row, value , label, column){
                      return getAssistCategory(value);
                    }},
		  {prop:'replaceStatus',label:'替换状态',dicData:repalceStatus(),type:'select',search:true,
                    formatter:function(row, value , label, column){
                      return getRepalceStatus(value);
                    }},
                  {prop:'sendTime',width:120,type:'date',label:'下发协查时间',format:'yyyy-MM-dd',valueFormat:'yyyy-MM-dd'},
                 
                  {prop:'sendPersonName',width:120,label:'下发人',}

                ]
              },
            }
        },
      computed: {
        ...mapGetters(["permissions"]),
        permissionList () {
          return {
            replaceContent: this.vaildData(
              this.permissions.tvm_dantai_one_click_replacement,
              false
            ),
            sendStatus: this.vaildData(
              this.permissions.tvm_dantai_issue_assistance,
              false
            ),
          };
        },
        // tableOption () {
        //   const { bankType } = this.extraParam;
        //   return tableOption[bankType];
        // },
        // bankType () {
        //   return this.extraParam.bankType;
        // },
      },
        created() {
          this.changeLine("9")
        },
        methods: {
          refreshChange() {
            this.getList()
          },
          cellStyle({ row, column, rowIndex,columnIndex }) {
            if(11==columnIndex){
              if (row.diffMoney < 0) {
                return {
                  color: "red",
                };
              }else if (row.diffMoney > 0) {
                return {
                  color: "green",
                };
              }
            }
          },
          rowStyle({ row, column, rowIndex }) {
            // if (row.diffMoney != 0 ) {
            //   return {
            //     backgroundColor: "#eee",
            //     color: "red",
            //   };
            // }
          },
          setSearchFiledsEmpty,
          getList() {
            this.listLoading = true;
            Object.assign(this.searchForm,this.page);
	    this.searchForm.assistCategoryRole='audit';//查询下发协查类型
            getSwAuTvmSingleAssistList(this.searchForm).then((response)=>{
              this.data = response.data.data
              this.listLoading = false
              this.page.total=response.data.total;
            });
          },
          selectionChange(list){
            this.selectKeys=list;
            this.selectKeyVals=[];
            for(let i=0;i<list.length;i++){
              this.selectKeyVals.push(list[i].id);
            }
          },
          handleFilter(params, done) {
            Object.assign(this.searchForm,params);
            this.getList()
            done()
          },
          replaceContent(){
            if(this.selectKeys.length<=0 || this.selectKeys.length>1 || this.isReplace()){
              this.$message.info("请选择一条未替换数据操作！");
              return;
            }
            this.isShowDia=true;
            this.$nextTick(()=>{
              this.$refs.HuikuiInfo.recallShow(this.selectKeyVals.join(","),this.selectKeys);
            })
          },
          previewEditor(row){ //回馈预览
            this.isShowDia=true;
            this.$nextTick(()=>{
              this.$refs.HuikuiInfo.recallShow(row.id,row,3);
            })
          },
          // replaceContentOne(row){ //一件替换
          //   this.isShowDia=true;
          //   this.$nextTick(()=>{
          //     this.$refs.HuikuiInfo.recallShow(row.id,[row],1);
          //   })
          // },
          replaceContentOne(){//一键替换
	  
           if(this.selectKeys.length<=0 || this.isAssistCategoryStatus()==false || this.isassistInvestStatus()==false|| this.isreplaceStatus()==false){
              this.$message.info("请选择协查含有机电部并且涉及部门已审核通过的并且未替换的数据！");
              return;
            }
	    /*
	    if(this.selectKeys.length<=0 || this.isassistInvestStatus()==false || this.isreplaceStatus()==false){
              this.$message.info("请选择协查流程为部门审核通过并且未替换的数据！");
              return;
            }*/
            if (!this.isReplyStatus()) {
              this.$message.info("请选择机电已回馈的数据！");
              return;
            }
            let ids=[];
            for(let i=0;i<this.selectKeys.length;i++){
              if(this.selectKeys[i].replaceStatus==0){
                ids.push(this.selectKeys[i].id);
              }
            }
            if(ids.length==0){
              this.$message.warning("无有效替换数据！");
              return;
            }
            setSwAuTvmSingleAssist({ids:ids.join(",")}).then(res=>{
              if(res.data.code==0){
                this.$message.success("操作成功！");
                this.getList();
                clearSelect(this.$refs.JieZhangDanAndSCCengji)
              }else{
                this.$message.error(res.data.msg);
              }
            })
          },

          isassistInvestStatus(){ // 是否协查
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
	      if(row.assistCategory=='2'||row.assistCategory=='3'){
	          if(row.assistInvestStatus!=8){
                      return false
                  }
	      }
             
            }
            return true;
          },
	  isAssistCategoryStatus(){ // 是否含有发机电的协查
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.assistCategory!='1' &&row.assistCategory!='3'){
                return false
              }
            }
            return true;
          },

          isReplyStatus(){ // 是否回馈
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.replyStatus==0){
                return false
              }
            }
            return true;
          },

          isreplaceStatus(){ // 是否替换
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.replaceStatus==1){
                return false
              }
            }
            return true;
          },
          // 下发协查（分三个按钮）
	async sendStatus(assistCategory) {
	  if (this.selectKeys.length <= 0) {
	    this.$message.warning("请选择下发数据！");
	    return;
	  }

	  let isSecondStation = 0;
	  let isSecondDevice = 0;
	  for (let i = 0; i < this.selectKeys.length; i++) {
	    let oldCategory = this.selectKeys[i].assistCategory;
	    if (oldCategory == 3) {
	      this.$message.warning("请选择未下发数据！");
	      return;
	    }
	    if (oldCategory == 1 && assistCategory == 1) {
	      this.$message.warning("选中的数据中存在之前已下发过设备部，不能再下发！");
	      return;
	    }
	    if (oldCategory == 1 && assistCategory == 3) {
	      this.$message.warning("选中的数据中存在之前已下发过设备部，不能再下发！");
	      return;
	    }
	    if (oldCategory == 2 && assistCategory == 2) {
	      this.$message.warning("选中的数据中存在之前已下发过车站，不能再下发！");
	      return;
	    }
	    if (oldCategory == 2 && assistCategory == 3) {
	      this.$message.warning("选中的数据中存在之前已下发过车站，不能再下发！");
	      return;
	    }
	    // 标记二次下发情况
	    if (oldCategory == 1 && assistCategory == 2) {
	      isSecondStation = 1;
	    }
	    if (oldCategory == 2 && assistCategory == 1) {
	      isSecondDevice = 1;
	    }
	  }
	  // 添加二次下发确认逻辑
	  if (isSecondStation || isSecondDevice) {
	    let confirmMessage = '';
	    let confirmTitle = '二次下发确认';

	    if (isSecondStation && assistCategory == 2) {
	      confirmMessage = '选中的数据中存在之前已经下发过设备部，再次下发给车站吗？';
	    } else if (isSecondDevice && assistCategory == 1) {
	      confirmMessage = '选中的数据中存在之前已经下发过车站，再次下发给设备部吗？';
	    }

	    this.$confirm(confirmMessage, confirmTitle, {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'warning'
	    }).then(() => {
	      // 用户确认后执行下发
	      this.executeSend(assistCategory);
	    }).catch(() => {
	      // 用户取消不做任何操作
	    });
	  } else {
	    // 正常下发时使用更合适的提示
	    let confirmMessage = '确定要下发选中的数据吗？';
	    let confirmTitle = '下发确认';

	    this.$confirm(confirmMessage, confirmTitle, {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'info'
	    }).then(() => {
	      this.executeSend(assistCategory);
	    }).catch(() => {
	      // 用户取消不做任何操作
	    });
	  }
	},   // 注意这里需要逗号分隔
	// 封装发送方法
	async executeSend(assistCategory) {
	  let messageLSList = [];
	  for (let i = 0; i < this.selectKeys.length; i++) {
	    let data = await getLineAndStationByCode({
	      "lineCode": this.selectKeys[i].lineCode,
	      "code": this.selectKeys[i].stationCode
	    });
	    messageLSList.push({
	      "content": "车站：" + data.data[0].name,
	      "lineCode": this.selectKeys[i].lineCode,
	      "stationCode": this.selectKeys[i].stationCode
	    });
	  }

	  let p = {
	    messageLSList: JSON.stringify(messageLSList),
	    title: this.$store.getters.tag.label,
	    msgType: "下发",
	    ids: this.selectKeyVals.join(','),
	    assistCategory: assistCategory,
	    ...(assistCategory === '1' && { jdType: "dantaishebeipiaohuanchayi_001" }),
	    ...(assistCategory === '2' && { kyType: "dantaishebeipiaohuanchayi_002" }),
	    ...(assistCategory === '3' && {
	      jdType: "dantaishebeipiaohuanchayi_001",
	      kyType: "dantaishebeipiaohuanchayi_002"
	    })
	  };

	  sendStatusSwAuTvmSingleAssist(p).then(res => {
	    if (res.data.code == 0) {
	      this.$message.success("操作成功！");
	      this.getList();
	    } else {
	      this.$message.error("操作失败！");
	    }
	  });
	} ,
        changeLine(v){ //改变线路时
            getgetStationCodes(v).then(res=>{
              this.stationCodes=res;
              this.searchForm.stationCode='';
            })
          },
          changeStation(v){ //改变车站
            let param={};
            param.lineCode=this.searchForm.lineCode;
            param.stationCode=v;
            getSwPmTvmCodeList(param).then(r=>{
              this.tvmCodes=r.data;
            });
          },
          isReplace(){ // 是否替换
            for(let i=0;i<this.selectKeys.length;i++){
              let row=this.selectKeys[i];
              if(row.replaceStatus==0){
                return false
              }
            }
            return true;
          },
          async exportData(){ // 导出
            this.searchForm.pageNo=1;
            this.searchForm.pageSize=1000000000;
            if(this.selectKeys.length>0){
              let newData = JSON.parse(JSON.stringify(this.selectKeys));
              exportDataToExcel(newData,this.option.column,'TVM单台设备票款差异协查');
            }else {
              let res=await getSwAuTvmSingleAssistList(this.searchForm);
              let data = res.data.data;
              exportDataToExcel(data,this.option.column,'TVM单台设备票款差异协查');
            }
          },
          delBatchs: function () {
            if (this.selectKeys.length<=0) {
              this.$message.error("请选择数据！");
              return false;
            }
            let ids = [];
            for(let i=0;i<this.selectKeys.length;i++){
              if (this.selectKeys[i].assistInvestStatus != "1" || this.selectKeys[i].kyAssistInvestStatus != "1") {
                this.$message.error("请检查数据，只能删除待下发的数据！");
                return false;
              }
              ids.push(this.selectKeys[i].id);
            }
            this.$confirm("确认删除?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              delBatch(ids)
                .then((data) => {
                  this.$message.success("删除成功");
                  this.getList(this.page);
                  done();
                })
                .catch(() => {
                  loading();
                });
            });
          },
          cancelChoose(){
            this.$refs.dantaishebeipiaohuanchayi.toggleSelection();
          },
          otherVueAction(){ //供其他Vue页面调用
            let th=this;
            transitUtil.$on('dantai_call',(param)=>{
              console.log(param);
              getSwAuTvmSingleAssistList({relationid:param.id}).then((response)=>{
                th.data = response.data.data;
                th.previewEditor(th.data[0]);
              });
            })
            transitUtil.$on('dantai_view',(param)=>{
              this.searchForm.relationid = param.id;
              this.getList();
            });
          }
        },
      mounted() {
        getLineCodes().then(res=>{ //获取线路
          this.lineCodes=res;
        });
        this.otherVueAction();
      }
    }
</script>
<style lang="scss">

</style>
